package com.sy.filter;

import com.sy.utils.ServletHolderUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用于通过ThreadLocal保存请求和响应的过滤器
 */
@WebFilter("/*")
public class Filter02_ServletHolderFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        //ThreadLocal保存请求和响应的过滤器
        ServletHolderUtils.setCurRequest(req);
        ServletHolderUtils.setCurResponse(res);
        filterChain.doFilter(req, res);
        //为了防止内存泄露，在这里移除之前绑定的对象
        ServletHolderUtils.removeCurReq();
        ServletHolderUtils.removeCurRes();
    }

    @Override
    public void destroy() {

    }
}
